import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/account/iview/below_user_takeout_score_page_iview.dart';
import 'package:flutter_deer/account/models/user_score_takeout_entity.dart';
import 'package:flutter_deer/account/presenter/below_user_takeout_score_presenter.dart';
import 'package:flutter_deer/account/provider/below_user_takeout_score_page_provider.dart';
import 'package:flutter_deer/account/widgets/rise_number_text.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/dimens.dart';
import 'package:flutter_deer/res/gaps.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/widgets/my_app_bar.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/widgets/my_refresh_list.dart';
import 'package:flutter_deer/widgets/state_layout.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class BelowUserTakeOutScorePage extends StatefulWidget {

  const BelowUserTakeOutScorePage({super.key});

  @override
  _BelowUserTakeOutScorePageState createState() => _BelowUserTakeOutScorePageState();
}

class _BelowUserTakeOutScorePageState extends State<BelowUserTakeOutScorePage> with BasePageMixin<BelowUserTakeOutScorePage, PowerPresenter>, AutomaticKeepAliveClientMixin<BelowUserTakeOutScorePage> implements BelowUserTakeOutScorePageIMvpView {

  final ScrollController _scrollController = ScrollController();

  BelowUserTakeOutScorePageProvider provider = BelowUserTakeOutScorePageProvider();

  bool get wantKeepAlive => false;

  late BelowUserTakeOutScorePresenter belowUserTakeOutScorePresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(
        this);
    belowUserTakeOutScorePresenter = new BelowUserTakeOutScorePresenter();
    powerPresenter.requestPresenter([belowUserTakeOutScorePresenter]);
    return powerPresenter;
  }

  @override
  void setBelowUserTakeOutScorePage(BelowUserScoreTakeoutPageEntity? pageEntity){
    provider.setBelowUserTakeOutScorePage(pageEntity);
  }

  @override
  void setStatistics(BelowUserScoreTakeoutStatisticsEntity? entity){
    provider.setStatistics(entity);
  }

  @override
  void initState() {
    super.initState();
    if(mounted){
      _onRefresh();
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    // provider.dispose();
    super.dispose();
  }

  Future<dynamic> _onRefresh() async {
    Future.delayed(Duration(seconds: 1),()=>{belowUserTakeOutScorePresenter.getTakeOutScorelist()});
  }

  Future<dynamic> _loadMore() async {
    belowUserTakeOutScorePresenter.getMoreTakeOutScoreList(provider.currentPage!+1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(centerTitle: '${DeerLocalizations.of(context)!.withdrawRecord.nullSafe}'),
        body: ChangeNotifierProvider<BelowUserTakeOutScorePageProvider>(
            create: (_) => provider,
            child:  Consumer<BelowUserTakeOutScorePageProvider>(
                    builder: (_,provider,child){
                      if(provider.stateType==StateType.loading||provider.statisticsStateType==StateType.loading){
                        return StateLayout(type: StateType.loading);
                      }
                      return DeerListView(
                          itemCount: provider.list!.length+1,
                          stateType: provider.stateType!,
                          onRefresh: _onRefresh,
                          loadMore: _loadMore,
                          hasMore: provider.hasMore!,
                          itemBuilder: (_, index) {
                            if(index>0) {
                              final BelowUserScoreTakeoutEntity item = provider.list!.elementAt(index-1);
                              return Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),
                                  child: MyCard(
                                      child: Padding(
                                          padding: const EdgeInsets.symmetric(horizontal: 5),
                                          child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: [
                                                Gaps.vGap5,
                                                Row(
                                                    children: <Widget>[
                                                      CircleAvatar(radius: 24.0,backgroundColor: Colors.transparent,backgroundImage: ImageUtils.getImageProvider(Constant.imageServerHost+'${item!.avatar}', holderImg: 'shop/tx')),
                                                      Gaps.hGap8,
                                                      Text('${DeerLocalizations.of(context)!.playerAccount.nullSafe}:${item!.accountId}')
                                                    ]
                                                ),
                                                Gaps.vGap8,
                                                Row(
                                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                    children: <Widget>[
                                                      Text('${DeerLocalizations.of(context)!.withdrawAmount.nullSafe}:${NumberFormat.decimalPattern('en_us').format(item!.score)}'),
                                                      Text('${DeerLocalizations.of(context)!.withdrawTime.nullSafe}:${item!.updateTime}'),
                                                    ]
                                                ),
                                                Gaps.vGap5
                                              ]
                                          )
                                      )
                                  )
                              );
                            }else{
                              return _buildCard(provider,provider.totalScore,provider.totalTimes);
                            }
                          }
                      );
                    }
                )));
  }

  Widget _buildCard(BelowUserTakeOutScorePageProvider provider,double? totalScore,int? totalTimes) {
    return AspectRatio(
        aspectRatio: 2.55,
        child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 6.0),
            padding: const EdgeInsets.all(6.0),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: ImageUtils.getAssetImage('account/bg'),
                fit: BoxFit.fill,
              ),
            ),
            child: provider.statisticsStateType==StateType.loading?Row(
                children: <Widget>[
                  _TakeOutStatistics(title: '${DeerLocalizations.of(context)!.accumulatedWithdraw.nullSafe}', count: '0',countFormat:'double'),
                  _TakeOutStatistics(title: '${DeerLocalizations.of(context)!.withdrawTimes.nullSafe}', count: '0',countFormat:'int'),
                ]
            ):Row(
                children: <Widget>[
                  _TakeOutStatistics(title: '${DeerLocalizations.of(context)!.accumulatedWithdraw.nullSafe}', count: '${totalScore}',countFormat:'double'),
                  _TakeOutStatistics(title: '${DeerLocalizations.of(context)!.withdrawTimes.nullSafe}', count: '${totalTimes}',countFormat:'int'),
                ]
            )
        )
    );
  }

}

class _TakeOutStatistics extends StatelessWidget {

  const _TakeOutStatistics({
    required this.title,
    required this.count,
    required this.countFormat,
    this.alignment,
    this.moneyTextStyle
  });

  final String title;
  final String count;
  final String countFormat;
  final MainAxisAlignment? alignment;
  final TextStyle? moneyTextStyle;

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: MergeSemantics(
        child: Column(
          mainAxisAlignment: alignment ?? MainAxisAlignment.center,
          children: <Widget>[
            /// 横向撑开Column，扩大语义区域
            const SizedBox(width: double.infinity),
            Text(title, style: const TextStyle(color: Colours.text_disabled, fontSize: Dimens.font_sp14)),
            Gaps.vGap8,
            countFormat=='double'?
            RiseNumberText(
                NumUtil.getDoubleByValueStr(count) ?? 0,
                style: moneyTextStyle ?? const TextStyle(
                    color: Colours.text_disabled,
                    fontSize: Dimens.font_sp14,
                    fontWeight: FontWeight.bold,
                    fontFamily: 'RobotoThin'
                )
            ):Text(count,style: moneyTextStyle ?? const TextStyle(
                color: Colours.text_disabled,
                fontSize: Dimens.font_sp14,
                fontWeight: FontWeight.bold,
                fontFamily: 'RobotoThin'
            )
            )
          ],
        ),
      ),
    );
  }
}